import React, { Component, Suspense } from 'react';
import PageLoading from '@/components/PageLoading';
import styles from "./index.less";
import { Button, Form, Spin, message, DatePicker, Input, Select, Icon, Table, Modal } from "antd";
import moment from 'moment';
import { connect } from 'dva';
import UpDownCharacter from '../../../modules/UpDownCharacter';
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const Option = Select.Option;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
	scriptUrl: '//at.alicdn.com/t/font_1131883_8lpmy5tq6hn.js', // 在 iconfont.cn 上生成
});
@connect(({ process, loading }) => ({
	process,
	loading: loading.effects['waitingLearningIssue/fetch'],
}))
class NewUnknownProblem extends Component {

	constructor() {
		super();
		this.state = {
			electb: "false",
			beginTime: "2020-06-05",
			overTime: "2020-06-05",
			login: true,
			selectedRowKeys: [],
			selectedRows: "",
			dataSource: [],
			total: "",
			selectedRows: null,
			asc: 'desc',
			pageSize: 15,
			page: 1,
			break: false,
			portJudge: true,
			upDownDate: [],
			loginjqr: false,
			question: "",
			query: "",
			showModel1: false,
			numberRadio: "1"
		}
	}

	componentWillMount() {
		let sysTime = moment().format('YYYY-MM-DD'); // 初始时间
		let toTime = moment().subtract('days', 7).format('YYYY-MM-DD');
		this.setState({ beginTime: toTime, overTime: sysTime, });
	}
	componentDidMount() {
		const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
		this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
	}

	fetch = (query, ignored, from, to, page, limit, order, sort) => {
		if (from && to) {
			this.setState({ login: true });
			const { dispatch, currentUser } = this.props;
			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: 'waitingLearningIssue/fetch',
					payload: { query, ignored, from, to, page, limit, order, sort },
					callback: res => {
						let temp = res.list;
						temp.map((item, index) => item['key'] = index);
						this.props.totala(res.total);
						this.setState({
							dataSource: temp,
							selectedRowKeys: [],
							total: res.total,
							selectedRows: null,
							login: false,
						})
					},
				});
			});
		} else {
			message.error(`请选择开始至结束日期`)
		}
	}

	handleRelete() {
		const { selectedRows, portJudge } = this.state;
		if (selectedRows) {
			let unknowIds = [];
			let title = "";
			let content = "";
			let url = "";
			selectedRows.map((item) => {
				unknowIds.push(item.id);
			});
			if (portJudge) {
				//忽略
				title = "忽略问题";
				content = "确定忽略吗？";
				url = "waitingLearningIssue/fetchc"
			} else {
				title = "恢复问题";
				content = "确定恢复吗？";
				url = "waitingLearningIssue/recovery"
			};
			Modal['confirm']({
				title,
				content,
				okText: "确认",
				cancelText: "取消",
				onOk: () => {
					this.ignoredOrRecoveryFetch(url, unknowIds);
				},
				onCancel() {

				}
			});
		} else {
			message['error']('您还没有选择！')
		}
	}

	//修改日期
	onChange(date, dateString) {
		this.setState({
			beginTime: dateString[0],
			overTime: dateString[1]
		});
	}
	//搜索
	handleSubmit() {
		let searchInfo = this.props.form.getFieldsValue();
		this.props.form.validateFields((err, values) => {
			if (!err) {
				let isLose = searchInfo.lose === "false" ? false : true;
				this.setState({ seek: searchInfo.seek, electb: searchInfo.lose, portJudge: !isLose, break: isLose, page: 1 }, () => {
					const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
					this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
				});
			}
		})
	}
	down() {

	}
	//关联
	handleOpen(row) {
		this.props.form.setFields({ "businessName": "" });
		this.setState({ question: row.question, query: '' }, () => {
			this.AnswerRelevance(this.state.question, this.state.field, this.state.query, 1, 10)
			this.setState({ showModel1: true, zuid: row.id })
		})
	}
	//获取关联列表数据
	AnswerRelevance(question, field, query, page = 1, pageSize = 10) {
		// this.setState({ logins: true });
		// const { dispatch, currentUser } = this.props;
		// dispatch({
		// 	type: 'waitingLearningIssue/fetchz',
		// 	payload: { robotId: currentUser.robotId, question, field, query, page, limit: pageSize },
		// 	callback: res => {
		// 		let aA = res.suggestList;
		// 		let bB = res.qaList;
		// 		let aALeng = res.suggestList.length;
		// 		let bBLeng = res.qaList.length;
		// 		const total = [...aA, ...bB];
		// 		total.map((item, index) => {
		// 			item['key'] = index;
		// 			// item['time'] = Number(item.updateTime)
		// 		});
		// 		this.setState({
		// 			total2: Number(res.total),
		// 			qaListTable: total,
		// 			logins: false,
		// 			aALeng: aALeng,
		// 			glLeng: Number(aALeng + bBLeng),
		// 		})
		// 	},
		// });
	}
	newlyAdded() {

	}
	//忽略/恢复 数据处理
	ignoredOrRecovery(row) {
		let unknowIds = [];
		let url = "";
		unknowIds.push(row.id);
		if (this.state.portJudge) {
			//忽略
			url = "waitingLearningIssue/fetchc";
		} else {
			//恢复
			url = "waitingLearningIssue/recovery";
		};
		this.ignoredOrRecoveryFetch(url, unknowIds);
	}

	//忽略/恢复 处理请求
	ignoredOrRecoveryFetch(url, unknowIds) {
		const { dispatch } = this.props;
		const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: url,
				payload: { unknowIds, ignored: this.state.portJudge },
				callback: res => {
					if (res.status === true) {
						message['success'](`${res.msg}`);
						this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
					}
				},
			});
		});
	}

	//关联modal下拉框
	onFromA() {

	}

	render() {
		const { getFieldDecorator } = this.props.form;
		const { selectedRowKeys } = this.state;
		const rowCheckSelection = {
			type: 'checkbox',
			selectedRowKeys, //告诉插件我们点击的哪一行
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedRowKeys,
					selectedRows: selectedRows
				})
			}
		};
		const columns = [
			{
				title: `未知问题`,
				width: 'calc(20vw)',
				dataIndex: 'question',
			},
			{
				title: '询问次数',
				width: 'calc(15vw)',
				dataIndex: 'count',
				sorter: (a, b) => { },
			},
			{
				title: '用户名',
				width: 'calc(15vw)',
				dataIndex: 'userName',
			},
			{
				title: '最近询问时间',
				width: 'calc(20vw)',
				dataIndex: 'updateTime',
				sorter: (a, b) => { },
				render: (updateTime) => {
					return moment(updateTime).format('YYYY-MM-DD HH:mm:ss');
				}
			},
			{
				title: '操作',
				width: 'calc(18vw)',
				render: (text, row) => {
					return (
						<div className={styles.wt}>
							<div className='zdyButtonA'>
								<Button type='primary' icon='link' size="small" onClick={() => this.handleOpen(row)}>关联</Button>
							</div>
							<div className='zdyButtonA'>
								<Button type="primary" htmlType='button' size='small' icon="plus" className={styles.processBtn} onClick={() => this.newlyAdded(row)}>新增</Button>
							</div>
							<div className='zdyButtonA'>
								<Button type="primary" icon="eye-invisible" htmlType='button' size='small' className={styles.processBtn} onClick={() => this.ignoredOrRecovery(row)}>
									{this.state.electb === 'false' ? "忽略" : "恢复"}
								</Button>
							</div>
							<UpDownCharacter
								text={text}
								name='上下文'
								icons='bars'
								title='聊天上下文'
								updowndate={this.state.upDownDate}
								onSubmitA={this.handleSubUpDwonDate}
								loginjqr={this.state.loginjqr}
								empty={this.empty}
							/>
						</div>
					)
				},
			}
		];
		return (
			<Suspense fallback={<PageLoading />}>
				<div style={{ padding: '0px 20px 0px 30px' }}>
					<div style={{ marginBottom: 20 }} className={styles.fromColumn}>
						<span className='zdyButtonA'>
							<Button style={{ marginTop: 10 }} onClick={this.handleRelete.bind(this)} type='primary' icon="eye-invisible">
								{this.state.electb === 'false' ? "批量忽略" : "批量恢复"}
							</Button>
						</span>
						<div>
							<Form className={styles.buttonA} layout="inline">
								<FormItem>
									<RangePicker
										onChange={this.onChange.bind(this)}
										style={{ width: 220 }}
										defaultValue={[
											moment(this.state.beginTime, dateFormat),
											moment(this.state.overTime, dateFormat),
										]}
										format={dateFormat}
									/>
								</FormItem>
								<FormItem>
									{getFieldDecorator('lose', {
										initialValue: this.state.electb,// 初始值
									})(
										<Select style={{ width: 130 }}>
											<Option value='false'>未忽略</Option>
											<Option value='true'>已忽略</Option>
										</Select>
									)}
								</FormItem>
								<FormItem>
									{getFieldDecorator('seek', {
										initialValue: '',// 初始值
									})(
										<Input onPressEnter={this.handleSubmit.bind(this)} placeholder="请输入搜索内容" />
									)}
								</FormItem>
								<FormItem className='buttonYs'>
									<Button onClick={this.handleSubmit.bind(this)} icon="search">搜索</Button>
								</FormItem>
								<FormItem className='buttonYs'>
									<Button onClick={this.down} icon="arrow-down">下载</Button>
								</FormItem>
							</Form>
						</div>
					</div>

					<Spin spinning={this.state.login}>
						<Table
							className='zdyTable'
							rowSelection={rowCheckSelection}
							style={{ padding: '0px 0px 0px 0px' }}
							columns={columns}
							dataSource={this.state.dataSource}//数据
							onChange={this.handleChange}
							pagination={{  // 分页
								total: Number(this.state.total),
								pageSize: this.state.pageSize,  // 显示几条一页
								current: this.state.page, // 当前页
								pageSizeOptions: ["15", "30", "50", "100"],
								showSizeChanger: true,  // 是否显示可以设置几条一页的选项
								showQuickJumper: true,
								onChange: this.onChangeA,
								onShowSizeChange: this.onShowSizeChangeA
							}}
						/>
					</Spin>

					<Modal
						style={{ top: 60 }}
						width={'calc( 70vw)'}
						className={styles.overa}
						title='添加关联知识点'
						visible={this.state.showModel1}
						footer={null}
						onCancel={() => {
							this.setState({ showModel1: false })
						}}
						onOk={() => {
							this.setState({ showModel1: false })
						}}
					>
						<Form layout="inline" style={{ paddingBottom: 20 }}>
							<FormItem style={{ marginLeft: 20 }}>
								<Select
									defaultValue={this.state.numberRadio}
									style={{ width: 160 }}
									onChange={this.onFromA}
								>
									<Option value='1'>搜索问题</Option>
									<Option value='2'>搜索答案</Option>
								</Select>
							</FormItem>
							<FormItem >
								{getFieldDecorator('businessName', {
									initialValue: '',
								})(
									<Search
										placeholder="请输入搜索内容"
										onSearch={value => {
											this.onFrom(value)
										}}
										style={{ width: 320 }}
									/>
								)}
							</FormItem>
						</Form>
						{/* <Spin spinning={this.state.logins}>
                            <Table
                                rowClassName={this.setClassName}
                                className={styles.over}
                                //  bordered
                                columns={columns1}
                                dataSource={this.state.qaListTable}
                                pagination={{  // 分页
                                    total: this.state.total2, // 数据总数量
                                    pageSize: this.state.glLeng,  // 显示几条一页
                                    current: this.state.pagetwo, // 当前页
                                    pageSizeOptions: [15, 30, 50, 100],
                                    showQuickJumper: true,
                                    onChange: this.handleSubmitComment,
                                    onShowSizeChange: this.handleSubmitComments
                                }}
                            />
                        </Spin> */}
					</Modal>
				</div>
			</Suspense>
		)
	}
}

export default connect(({ user }) => ({ // 全局数据 portJudge
	currentUser: user.currentUser,
}))(Form.create()(NewUnknownProblem));
